import 'package:sqflite/sqflite.dart';
import '../database/database_helper.dart';
import '../models/information.dart';

class InformationService {
  final dbHelper = DatabaseHelper.instance;

  Future<int> insertInformation(Information information) async {
    Database db = await dbHelper.database;
    return await db.insert('information', information.toMap());
  }

  Future<int> updateInformation(Information information) async {
    Database db = await dbHelper.database;
    return await db.update(
      'information',
      information.toMap(),
      where: 'id = ?',
      whereArgs: [information.id],
    );
  }

  Future<int> deleteInformation(int id) async {
    Database db = await dbHelper.database;
    return await db.delete(
      'information',
      where: 'id = ?',
      whereArgs: [id],
    );
  }

  Future<Information?> getInformationById(int id) async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'information',
      where: 'id = ?',
      whereArgs: [id],
    );

    if (maps.isNotEmpty) {
      return Information.fromMap(maps.first);
    }
    return null;
  }

  Future<List<Information>> getAllInformation() async {
    Database db = await dbHelper.database;
    List<Map<String, dynamic>> maps = await db.query(
      'information',
      orderBy: 'publishDate DESC',
    );
    return List.generate(maps.length, (i) => Information.fromMap(maps[i]));
  }
}
